<template>
  <div class="game-window powerpoint-window">
    <!-- PowerPoint标题栏 -->
    <div class="window-header">
      <div class="window-controls">
        <img src="@/assets/icons/powerpoint.svg" class="app-icon" />
        <span class="title">演示文稿1.pptx - PowerPoint</span>
      </div>
      <div class="window-buttons">
        <span class="minimize">─</span>
        <span class="maximize">□</span>
        <span class="close" @click="$router.push('/')">×</span>
      </div>
    </div>

    <!-- PowerPoint功能区 -->
    <div class="powerpoint-ribbon">
      <div class="quick-access-toolbar">
        <button class="save-button"><i class="fas fa-save"></i></button>
        <button class="undo-button"><i class="fas fa-undo"></i></button>
      </div>
      
      <div class="ribbon-tabs">
        <div class="tab active">文件</div>
        <div class="tab">开始</div>
        <div class="tab">插入</div>
        <div class="tab">设计</div>
        <div class="tab">切换</div>
        <div class="tab">动画</div>
        <div class="tab">幻灯片放映</div>
        <div class="tab">视图</div>
      </div>

      <div class="ribbon-content">
        <div class="ribbon-group">
          <div class="group-title">幻灯片放映</div>
          <div class="group-content">
            <button @click="toggleDisguise">
              <i class="fas fa-play"></i>
              <span>开始放映</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 游戏区域 -->
    <div class="game-content" :class="{ 'disguise': isDisguised }">
      <!-- 伪装模式 -->
      <div v-if="isDisguised" class="disguise-content">
        <div class="slideshow">
          <h2>正在准备幻灯片放映...</h2>
          <div class="progress-bar"></div>
          <p>正在加载动画效果</p>
        </div>
      </div>
      
      <!-- 游戏画布 -->
      <div v-else class="puzzle-container">
        <div class="puzzle-grid">
          <div 
            v-for="(tile, index) in tiles" 
            :key="index"
            class="puzzle-tile"
            :class="{ 'empty': tile.value === tiles.length - 1 }"
            :style="getTileStyle(tile)"
            @click="moveTile(index)"
          >
            {{ tile.value === tiles.length - 1 ? '' : tile.value + 1 }}
          </div>
        </div>
        
        <div class="puzzle-controls">
          <button @click="shuffleTiles">重新打乱</button>
          <div class="moves">移动次数: {{ moves }}</div>
          <div class="time">用时: {{ formatTime(gameTime) }}</div>
        </div>
      </div>
    </div>

    <!-- 缩略图面板 -->
    <div class="thumbnails-panel">
      <div class="thumbnail active">
        <div class="slide-preview"></div>
        <div class="slide-number">1</div>
      </div>
    </div>

    <!-- 状态栏 -->
    <div class="powerpoint-statusbar">
      <div class="status-item">幻灯片 1/1</div>
      <div class="zoom-control">
        <span>100%</span>
        <input type="range" min="10" max="200" value="100">
      </div>
    </div>

    <!-- 广告区域 -->
    <div class="ad-container">
      <div id="puzzle-ad"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const isDisguised = ref(false)
const tiles = ref([])
const moves = ref(0)
const gameTime = ref(0)
let timer = null

// 游戏配置
const GRID_SIZE = 3
const TOTAL_TILES = GRID_SIZE * GRID_SIZE

// 初始化游戏
const initGame = () => {
  // 创建有序的拼图块
  tiles.value = Array.from({ length: TOTAL_TILES }, (_, i) => ({
    value: i,
    currentPos: i,
    targetPos: i
  }))
  
  moves.value = 0
  gameTime.value = 0
  startTimer()
  shuffleTiles()
}

// 获取拼图块样式
const getTileStyle = (tile) => {
  const row = Math.floor(tile.targetPos / GRID_SIZE)
  const col = tile.targetPos % GRID_SIZE
  
  return {
    backgroundColor: tile.value === TOTAL_TILES - 1 ? 'transparent' : '#B4009E',
    transform: `translate(${(tile.currentPos % GRID_SIZE - col) * 100}%, ${(Math.floor(tile.currentPos / GRID_SIZE) - row) * 100}%)`
  }
}

// 移动拼图块
const moveTile = (index) => {
  if (isDisguised.value) return
  
  const tile = tiles.value[index]
  const emptyTile = tiles.value.find(t => t.value === TOTAL_TILES - 1)
  
  // 检查是否相邻
  const canMove = (
    (Math.abs(tile.currentPos - emptyTile.currentPos) === 1 && 
     Math.floor(tile.currentPos / GRID_SIZE) === Math.floor(emptyTile.currentPos / GRID_SIZE)) ||
    Math.abs(tile.currentPos - emptyTile.currentPos) === GRID_SIZE
  )
  
  if (canMove) {
    // 交换位置
    const tempPos = tile.currentPos
    tile.currentPos = emptyTile.currentPos
    emptyTile.currentPos = tempPos
    
    moves.value++
    checkWin()
  }
}

// 检查是否完成
const checkWin = () => {
  const isWin = tiles.value.every(tile => tile.currentPos === tile.targetPos)
  
  if (isWin) {
    setTimeout(() => {
      alert(`恭喜完成！\n移动次数：${moves.value}\n用时：${formatTime(gameTime.value)}`)
      shuffleTiles()
    }, 300)
  }
}

// 打乱拼图
const shuffleTiles = () => {
  let solvable
  do {
    // 随机打乱
    for (let i = tiles.value.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1))
      const tempPos = tiles.value[i].currentPos
      tiles.value[i].currentPos = tiles.value[j].currentPos
      tiles.value[j].currentPos = tempPos
    }
    
    // 检查是否可解
    solvable = checkSolvable()
  } while (!solvable)
  
  moves.value = 0
  gameTime.value = 0
}

// 检查拼图是否可解
const checkSolvable = () => {
  let inversions = 0
  const tileValues = tiles.value.map(t => t.value)
  
  for (let i = 0; i < tileValues.length - 1; i++) {
    for (let j = i + 1; j < tileValues.length; j++) {
      if (tileValues[i] > tileValues[j] && tileValues[i] !== TOTAL_TILES - 1 && tileValues[j] !== TOTAL_TILES - 1) {
        inversions++
      }
    }
  }
  
  const emptyTileRow = Math.floor(tiles.value.find(t => t.value === TOTAL_TILES - 1).currentPos / GRID_SIZE)
  
  return GRID_SIZE % 2 === 1 ? 
    inversions % 2 === 0 : 
    (inversions + emptyTileRow) % 2 === 1
}

// 切换伪装模式
const toggleDisguise = () => {
  isDisguised.value = !isDisguised.value
}

// 计时器
const startTimer = () => {
  if (timer) clearInterval(timer)
  timer = setInterval(() => {
    gameTime.value++
  }, 1000)
}

// 格式化时间
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 键盘事件
const handleKeyDown = (event) => {
  if (event.key === 'Escape') {
    toggleDisguise()
  }
}

onMounted(() => {
  initGame()
  window.addEventListener('keydown', handleKeyDown)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
  window.removeEventListener('keydown', handleKeyDown)
})
</script>

<style lang="scss" scoped>
@use "sass:color";

.powerpoint-window {
  .window-header {
    background: #B4009E;
    color: white;
  }

  .powerpoint-ribbon {
    background: #F3F2F1;
    border-bottom: 1px solid #E1DFDD;
    
    .ribbon-tabs {
      .tab {
        &.active {
          color: #B4009E;
          border-bottom: 2px solid #B4009E;
        }
      }
    }
  }

  .puzzle-container {
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;

    .puzzle-grid {
      width: 300px;
      height: 300px;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 2px;
      background: #E1DFDD;
      padding: 2px;
      border-radius: 4px;

      .puzzle-tile {
        position: relative;
        background: #B4009E;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        font-weight: bold;
        cursor: pointer;
        transition: transform 0.2s ease;
        
        &.empty {
          background: transparent;
          cursor: default;
        }
        
        &:hover:not(.empty) {
          filter: brightness(1.1);
        }
      }
    }

    .puzzle-controls {
      display: flex;
      gap: 20px;
      align-items: center;

      button {
        padding: 8px 16px;
        background: #B4009E;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        
        &:hover {
          background: color.adjust(#B4009E, $lightness: -10%);
        }
      }
    }
  }

  .thumbnails-panel {
    width: 200px;
    border-right: 1px solid #E1DFDD;
    padding: 10px;

    .thumbnail {
      padding: 5px;
      cursor: pointer;
      
      &.active {
        background: rgba(#B4009E, 0.1);
      }

      .slide-preview {
        width: 100%;
        aspect-ratio: 16/9;
        background: white;
        border: 1px solid #E1DFDD;
      }

      .slide-number {
        text-align: center;
        font-size: 12px;
        color: #666;
        margin-top: 4px;
      }
    }
  }

  .disguise-content {
    .slideshow {
      text-align: center;
      padding: 40px;
      
      .progress-bar {
        width: 300px;
        height: 20px;
        background: #f0f0f0;
        margin: 20px auto;
        position: relative;
        overflow: hidden;
        
        &::after {
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          height: 100%;
          width: 30%;
          background: #B4009E;
          animation: progress 2s infinite linear;
        }
      }
    }
  }
}

@keyframes progress {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(400%); }
}
</style> 